package com.sanpu.kxe.business.trade.presenter;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.sanpu.kxe.R;
import com.sanpu.kxe.business.card.bean.BankInfoOutput;
import com.sanpu.kxe.business.card.provider.ICardProvider;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.business.main.bean.UserConfigOutput;
import com.sanpu.kxe.business.main.provider.IMainProvider;
import com.sanpu.kxe.business.trade.bean.PayCollectionOutput;
import com.sanpu.kxe.business.trade.bean.PayLimit;
import com.sanpu.kxe.business.trade.contract.PersonalGatheringContract;
import com.sanpu.kxe.business.trade.model.TradeModel;
import com.sanpu.kxe.business.trade.provider.TradeOpenProvider;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.enums.PayType;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.common.interfaces.DialogViewListener;
import com.sanpu.kxe.common.interfaces.UrlConstants;
import com.sanpu.kxe.module.dialog.GlobalDialog;
import com.sanpu.kxe.rxservice.RequestMap;
import com.sanpu.kxe.utils.DateUtils;
import com.sanpu.kxe.utils.DialogUtil;
import com.sanpu.kxe.utils.PublicProviderUtil;
import com.sanpu.kxe.utils.ToastUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：个人收款
 * Created by 薛勇军 on 2019/9/25.
 */

public class PersonalGatheringPresenter implements PersonalGatheringContract.Presenter {

    private PersonalGatheringContract.View mView;

    private CompositeSubscription mSubscription;

    public PersonalGatheringPresenter(PersonalGatheringContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
        final UserCenterOutput retDatBean = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        if (retDatBean == null || !TextUtils.equals(CommonConfig.AUTHEN_PASS, retDatBean.getChkSts())) {
            String btnText = "", contentText = "";
            switch (retDatBean.getChkSts()) {
                case CommonConfig.AUTHEN_NOTSUB:
                    btnText = "去认证";
                    contentText = "收款前请先完成认证";
                    break;
                case CommonConfig.AUTHEN_AUDIT:
                    btnText = "确定";
                    contentText = "您的实名认证正在审核中，请稍后";
                    break;
                case CommonConfig.AUTHEN_NOPASS:
                    btnText = "重新认证";
                    contentText = "您的实名认证审核失败，请重新认证";
                    break;
                case CommonConfig.AUTHEN_NOCOMPLETION:
                    btnText = "去补全";
                    contentText = "需要补全资料才能开启收款";
                    break;
            }
            DialogUtil.getInstance().dialogNoTitletTwoBtnHaveCallBack(mView.getContext(), contentText, "取消", btnText,
                    new DialogViewListener() {
                        @Override
                        public void btnRightConfirm() {
                            if (!TextUtils.equals(CommonConfig.AUTHEN_AUDIT, retDatBean.getChkSts())) {
                                openCertificationActivity();
                            }
                        }

                        @Override
                        public void btnLeftCancel() {

                        }
                    });
        }
    }

    @Override
    public void selectUrmBankPage() {
        final ICardProvider provider = PublicProviderUtil.getProvider(ICardProvider.class);
        if (provider != null) {
            Subscription subscription = provider.selectUrmBankPage("")
                    .subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<BankInfoOutput>>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(List<BankInfoOutput> bankInfoOutputs) {
                            if (bankInfoOutputs == null || bankInfoOutputs.size() == 0) {
                                provider.openAddBankSetupActivity(mView.getContext(), true);
                                return;
                            }
                            dealBankData(bankInfoOutputs);
                        }
                    });
            mSubscription.add(subscription);
        }
    }

    /**
     * 筛选银行卡列表
     */
    private void dealBankData(List<BankInfoOutput> bankInfoOutputs) {
        List<BankInfoOutput> mOutBankList = new ArrayList<>();
        List<BankInfoOutput> mInBankList = new ArrayList<>();
        for (BankInfoOutput data : bankInfoOutputs) {
            if (CommonConfig.CREDIT_CARD_TYPE.equals(data.getCardType())) {
                mOutBankList.add(data);
            }
            if (CommonConfig.DEPOSIT_CARD_TYPE.equals(data.getCardType()) && data.isDefStlFlg()) {
                mInBankList.add(data);
                if (data.isDefStlFlg())
                    mView.showBankInfo(data, false);
            }
        }

        if (!mOutBankList.isEmpty()) {
            mView.showBankInfo(mOutBankList.get(0), true);
        }

        mView.setBankListData(mOutBankList, mInBankList);
    }

    @Override
    public void collectionList(String collectionType) {
        mView.showLoadingDialog(true);
        Subscription subscription = TradeModel.getInstance().appCnlConfList(collectionType)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<PayCollectionOutput>>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(List<PayCollectionOutput> payCollectionOutputs) {
                        if (payCollectionOutputs != null && payCollectionOutputs.size() > 0) {
                            mView.showListDataView(payCollectionOutputs);
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public boolean checkInputMoney(String gatheringMoney) {
        try {
            UserConfigOutput configOutput = CacheManage.getInstance().getCache(CacheModel.USER_CONFIG);
            PayLimit payLimit = new PayLimit(configOutput.getAppFasterMinAmt(), configOutput.getAppFasterMaxAmt());
            BigDecimal amt = new BigDecimal(gatheringMoney);
            if (!TextUtils.isEmpty(payLimit.getMin() + "") && amt.compareTo(payLimit.getMin()) == -1) {
                ToastUtil.showTextViewPrompt("收款最低为￥" + payLimit.getMin());
                return false;
            }
            if (!TextUtils.isEmpty(payLimit.getMax() + "") && amt.compareTo(payLimit.getMax()) == 1) {
                ToastUtil.showTextViewPrompt("收款最高为￥" + payLimit.getMax() + "单笔");
                return false;
            }
        } catch (Exception e) {
            ToastUtil.showTextViewPrompt("收款限额数据异常");
            return false;
        }
        return true;
    }

    @Override
    public boolean checkCollectionPay(PayCollectionOutput collectionOutput, String inputText) {
        try {
            if (TextUtils.equals("DISABLE", collectionOutput.getEnableStatus())) {
                GlobalDialog dialog = new GlobalDialog(mView.getContext())
                        .content(collectionOutput.getDisableReason())
                        .headerIcon(R.drawable.img_fail_result);
                dialog.show();
                return false;
            }
            String payTime = collectionOutput.getTradeStartTime() + "," + collectionOutput.getTradeEndTime();
            if (!DateUtils.isSupportPaymentTime(payTime)) {
                String[] tranTm = payTime.split(",");
                new GlobalDialog(mView.getContext())
                        .content("暂时不能支付，支付时间段：(" + tranTm[0] + "-" + tranTm[1] + ")。").show();
                return false;
            }
            PayType mPayType = null;
            try {
                mPayType = PayType.valueOf(collectionOutput.getBusinessType());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (mPayType == null) {
                ToastUtil.showTextViewPrompt("该支付方式暂不可用，请尝试其他");
                return false;
            }
            PayLimit payLimit = new PayLimit(collectionOutput.getMinTradeAmount(), collectionOutput.getMaxTradeAmount());
            BigDecimal amt = new BigDecimal(inputText);
            if (amt.compareTo(payLimit.getMin()) == -1) {
                ToastUtil.showTextViewPrompt(mPayType.getTitle() + "最低为￥" + payLimit.getMin());
                return false;
            }
            if (amt.compareTo(payLimit.getMax()) == 1) {
                ToastUtil.showTextViewPrompt(mPayType.getTitle() + "最高为￥" + payLimit.getMax() + "单笔");
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override
    public double getGatherFee(PayCollectionOutput collectionOutput, String inputText) {
        List<PayCollectionOutput.RateDetail> rateDetails = collectionOutput.getRateDetails();
        String tradeRate = "0", otherFeeAmt = "0";
        if (rateDetails != null) {
            if (rateDetails.size() == 1) {
                tradeRate = rateDetails.get(0).getTradeRate();
                otherFeeAmt = rateDetails.get(0).getExtraCharge();
            } else {
                for (PayCollectionOutput.RateDetail rateDetail : rateDetails) {
                    if (!TextUtils.equals("VIP", rateDetail.getMerchantLevel())) {
                        tradeRate = rateDetail.getTradeRate();
                        otherFeeAmt = rateDetail.getExtraCharge();
                        break;
                    }
                }
            }
        }
        double needFee = Double.valueOf(inputText) * Double.valueOf(tradeRate) / 100;
        String maxFeeAmt = collectionOutput.getCapAmount();
        if (!TextUtils.isEmpty(maxFeeAmt)) {
            double maxFee = Double.parseDouble(maxFeeAmt);
            if (maxFee > 0 && maxFee < needFee) {
                needFee = maxFee;
            }
        }
        double otherFee = 0.00;
        if (!TextUtils.isEmpty(otherFeeAmt)) {
            otherFee = Double.parseDouble(otherFeeAmt);
        }
        return needFee + otherFee;
    }

    @Override
    public void onComfirmPay(String outBankId, String inBankId, String appCnlConfId, String payAmount) {
        JSONObject reqData = new JSONObject();
        reqData.put("payBankId", outBankId);
        reqData.put("stlBankId", inBankId);
        reqData.put("payAmount", payAmount);
        reqData.put("appCnlConfId", appCnlConfId);
        RequestMap requestMap = new RequestMap();
        requestMap.put(CommonConfig.REQDATA, new Gson().toJson(reqData));
        TradeOpenProvider.getInstance().openQuickPayWebViewActivity(mView.getContext(),
                UrlConstants.URL_QUICKPAYH5, requestMap.map2ReqStr().replace("+", "%2B"));
    }

    /**
     * 去认证
     */
    private void openCertificationActivity() {
        IMainProvider mainProvider = PublicProviderUtil.getProvider(IMainProvider.class);
        if (mainProvider != null) {
            mainProvider.openCertificationActivity(mView.getContext(), true);
        }
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
